#include "jinyan.h"
#include "ui_jinyan.h"
#include <QMessageBox>
#include <QDebug>

jinyan::jinyan(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::jinyan)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &jinyan::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &jinyan::onReadyRead);
    connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &jinyan::onError);

    socket->connectToHost("192.168.159.131", 1234);
}

jinyan::~jinyan()
{
    delete ui;
}

void jinyan::onConnected() {
    qDebug() << "已连接到服务器！";
}

void jinyan::onReadyRead() {
    QByteArray data = socket->readAll();
    QDataStream stream(&data, QIODevice::ReadOnly);
    QString message;
    stream >> message;

    int spaceIndex = message.indexOf('\n'); // 寻找第一个空格的位置

    QString responseType = message.left(spaceIndex);
    QString Data = message.mid(spaceIndex + 1);

    if (responseType == "JINYAN2_SUCCESS") {
        QMessageBox::information(this, "提示", "禁言成功");
        this->close();  // 关闭当前窗口
    } else if (responseType == "JINYAN2_FAIL") {
        QMessageBox::warning(this, "提示", "请输入正确用户名");
    }
}

void jinyan::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}

void jinyan::on_queren_clicked()
{
    QString username = ui->yonghuming->text();
    if (username.isEmpty()) {
        QMessageBox::warning(this, "提示", "用户名不能为空");
    } else {
        // 向服务器发送禁言信息
        QString message = "JINYAN2\n";
        message += username + "\n";
        socket->write(message.toUtf8());

        qDebug() << "发送信息";
    }
}

void jinyan::on_fanhui_clicked()
{
    this->close();
}
